import asyncio
import json
import os

import aiofiles
from alibabacloud_ocr_api20210707 import models as OCRModels
from alibabacloud_ocr_api20210707.client import Client
from alibabacloud_tea_openapi import models as OpenApiModels
from alibabacloud_tea_util import models as UtilModels


def make_ocr_client(
    access_key_id: str | None = None,
    access_key_secret: str | None = None,
    ocr_endpoint: str | None = None,
) -> Client:
    access_key_id = access_key_id or os.environ["ACCESS_KEY_ID"]
    access_key_secret = access_key_secret or os.environ["ACCESS_KEY_SECRET"]
    config = OpenApiModels.Config(
        access_key_id=access_key_id,
        access_key_secret=access_key_secret,
    )
    config.endpoint = ocr_endpoint or os.environ["OCR_ENDPOINT"]
    client = Client(config)
    return client


client = make_ocr_client()


async def id_card_ocr(img_url: str) -> OCRModels.RecognizeIdcardResponse:
    """身份证识别"""
    request = OCRModels.RecognizeIdcardRequest(
        url=img_url,
    )
    runtime = UtilModels.RuntimeOptions()
    res = await client.recognize_idcard_with_options_async(request, runtime)
    return res


async def __test():
    res = await id_card_ocr(
        "https://img.alicdn.com/tfs/TB1q5IeXAvoK1RjSZFNXXcxMVXa-483-307.jpg"
    )
    res_dict = res.body.to_map()
    async with aiofiles.open("temp.json", "w", encoding="utf-8") as f:
        await f.write(json.dumps(res_dict, ensure_ascii=False, indent=4))

    print(json.dumps(json.loads(res_dict["Data"]), ensure_ascii=False, indent=4))


if __name__ == "__main__":
    asyncio.run(__test())
